import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { RequestContextService } from '../../auth/common/services/request-context.service';
import { RbacService } from '../rbac.service';
import { ROLES_KEY } from '../decorators/roles.decorator';

/**
 * 角色守卫
 * 检查用户是否拥有所需角色（基于 CLS）
 */
@Injectable()
export class RolesGuard implements CanActivate {
  constructor(
    private reflector: Reflector,
    private rbacService: RbacService,
    private requestContext: RequestContextService
  ) {}

  canActivate(context: ExecutionContext): boolean {
    const requiredRoles = this.reflector.getAllAndOverride<string[]>(ROLES_KEY, [
      context.getHandler(),
      context.getClass(),
    ]);

    if (!requiredRoles) {
      return true;
    }

    // 从 CLS 获取用户角色
    const userRoles = this.requestContext.getCurrentUserRoles();

    if (!userRoles || userRoles.length === 0) {
      return false;
    }

    return this.rbacService.hasRole(userRoles, requiredRoles);
  }
}

